import { getPublicKey } from '@/api/auth/auth';
import { sm2, sm3, sm4 } from 'sm-crypto'
import { store } from "@/store";
export const useCryptoStore = defineStore("crypto", () => {

    //公钥
    const publicKey = ref("");
    //私钥
    const privateKey = ref("");

    //加密
    const doEncrypt =async   (text: string) => {

        //如果公钥为空，则请求接口返回公钥
        if(!publicKey.value){
           publicKey.value=await getPublicKey();
        }

            // console.log("公钥为空");
        //     initPublicKey();
        //     ElMessage.error("网络请求失败");
        //     new Error("公钥为空"); //抛出异常
        // }
        // else{
            return sm2.doEncrypt(text, publicKey.value) as string;
        // }
        
    
       
  
     
    }
    //解密
    const doDecrypt = (text: string) => {
        return sm2.doDecrypt(text, privateKey.value) as string;
    }

    //获取公钥

    const initPublicKey=async ()=>{

        console.log("请求接口返回公钥");
        //如果公钥为空，则请求接口返回公钥
        if(!publicKey.value){
           const res=await getPublicKey();
           publicKey.value=res;
        }

    }


    return{
        initPublicKey,publicKey,doEncrypt,doDecrypt
    }




})

export function useCryptoStoreHook() {
    return useCryptoStore(store);
  }
  